package com.yunfei.yikao.web.controlller;


import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;

/**
 * @Author: yunfei
 * @Date: 14:12
 */
@Controller
public class CaptchaControl {
    @Autowired
    private DefaultKaptcha kaptcha;

    //    设置HTTP Cache响应头
    @RequestMapping(path = "/captcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
//        set to expir far in the past.
        response.setDateHeader("Expires", 0);
//        set standard HTTP/1.1 no-cahce heaeders.
        response.setHeader("Cache-Control", "no-cache,must-revalidate");
//        set IE extended HTTP/1.1 no-cahce header (use addHeader);
        response.addHeader("Cache-Control", "post-check=0,pre-check=0");
//        set standard HTTP/1.0 no-cahce header.
        response.setHeader("Pragma", "no-cache");
//        设置内容格式
        response.setContentType("image/png");
//        创建随机数
        String capText = kaptcha.createText();
//        store the text in the image
//        将随机数存储到session里面
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
//          图片的输出
        BufferedImage bi = kaptcha.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "png", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }



    //    Spring 启动时初始化Bean实例
    @Bean
    public DefaultKaptcha initKaptcha(){

        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.put(Constants.KAPTCHA_IMAGE_WIDTH,"120");
        properties.put(Constants.KAPTCHA_IMAGE_HEIGHT,"40");
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE,"32");
        Config config=new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }

}
